package com.chakid.dbf;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.linuxense.javadbf.DBFField;
import com.linuxense.javadbf.DBFReader;
import com.mysql.jdbc.Connection;


/**
 * 创建数据库的表格
 * @author Yuan
 *
 */
public class CreateTab {

	private static String table;// 表格名称;
	private static StringBuffer params;// 记录表格各字段
	
	private static List<String> sqlCrea;// 创建表语句

	private static Connection con = null;
	private static java.sql.Statement stm = null;
	private static ResultSet res = null;
	
	

	public static void readDBF(String path) throws SQLException, IOException {

		table = Const.LAST_PATH;
		params = new StringBuffer("(");
		sqlCrea = new ArrayList<String>();

		InputStream fis = null;
		try {
			// 读取文件的输入流
			fis = new FileInputStream(path);
			// 根据输入流初始化一个DBFReader实例，用来读取DBF文件信息
			DBFReader reader = new DBFReader(fis);
			
			reader.setCharactersetName("GBK");
			// 调用DBFReader对实例方法得到path文件中字段的个数
			int fieldsCount = reader.getFieldCount();
			// 取出字段信息
			for (int i = 0; i < fieldsCount; i++) {
				DBFField field = reader.getField(i);
				// 字段名
				params.append("`"+field.getName()+"`" +" VARCHAR(156)"+ ",");
				
			}
		
			
			
			
			params.deleteCharAt(params.length() - 1);
			params.append(")");
					
					
			
			
			// 生成插入语句字符串
			
			sqlCrea.add("create table " + "`" + table + "`"+ params.toString());
			
			System.out.println(sqlCrea);
			
		

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
			
		ReadDBF.dbf_Import(sqlCrea);
		
		 //关闭输入流
        fis.close();
        //关闭数据库连接
        DBConnect.close(null, stm, con);
		

	}

	public static void dbf_Import(List sql) throws SQLException {
		// 打开数据库连接
		con = DBConnect.getConnection();

		stm = con.createStatement();
		int i = 0;
		for (; i < sql.size(); i++) {
			// 将sql语句加入批处理中
			stm.addBatch((String) sql.get(i));
		}
		// 执行批处理
		System.out.println("开始插入数据");
		stm.executeBatch();
		System.out.println("插入数据成功");

	}
	

	public static void main(String[] args) throws SQLException, IOException {
				CreateTab.readDBF("d:/t_tdds.dbf");

	}
}
